package com.atguigu.service.impl;

import com.atguigu.bean.*;
import com.atguigu.dao.BookDao;
import com.atguigu.dao.OrderDao;
import com.atguigu.dao.OrderItemDao;
import com.atguigu.dao.impl.BookDaoImpl;
import com.atguigu.dao.impl.OrderDaoImpl;
import com.atguigu.dao.impl.OrderItemDaoImpl;
import com.atguigu.service.OrderService;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

public class OrederServiceImpl implements OrderService {
    private  OrderDao orderDao =new OrderDaoImpl();
    private  OrderItemDao orderItemDao = new OrderItemDaoImpl();
    private BookDao bookDao = new BookDaoImpl();
    @Override
    public String createOrder(Cart cart, User user) {
        /**
         * ①：创建一个Order对象（），通过dao层添加数据
         * ②：创建n个订单（OrderItem），通过dao层添加数据库
         * ③：修改图书的库存和销量
         */
        //随机生成一个订单号不重复(可以用时间戳精确到毫秒数)
        String l = "atGuiGU"+System.currentTimeMillis()+"";
        System.out.println("l = " + l);
        //时间
        LocalDateTime now = LocalDateTime.now();
        //进行格式化
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = formatter.format(now);

        Order order=new Order(0,l,format,cart.getTotalCount(),cart.getTotalAmount(),0,user.getId());
        orderDao.addOrder(order);
         int orderId= orderDao.findOrderId(l);
         List<CartItem> allCartItem= cart.getAllCartItem();
         for (CartItem cartItem : allCartItem){
             OrderItem orderItem=new OrderItem(
                     0,
                     cartItem.getBook().getTitle(),
                     cartItem.getBook().getPrice(),
                     cartItem.getBook().getImg_path(),
                     cartItem.getCount(),
                     cartItem.getAmount(),
                     orderId);
             orderItemDao.addOrderItem(orderItem);
             Book book =cartItem.getBook();
             book.setSales(book.getSales()+cartItem.getCount());
             book.setStock(book.getStock()-cartItem.getCount());
             bookDao.updateBookById(book);
         }
         return l;
    }

    @Override
    public List<Order> findAllOrderById(int id) {
        return orderDao.findAllOrderById(id);
    }
}
